<template>
  <div class="background-manage">

    <div v-if="previewUrl" class="preview-section">
      <div class="preview-header">
        <h4>图片预览</h4>
        <button @click="clearPreview" class="btn clear-btn">清除</button>
      </div>
        <img :src="previewUrl" alt="Image Preview" class="preview-image" @click="openModal(previewUrl)"/>
    </div>

    <div class="upload-section">
      <input type="file" @change="handleFileChange" accept="image/*" ref="fileInput" class="file-input">
      <button @click="triggerFileInput" class="btn upload-btn">选择图片</button>
      <button @click="handleUpload" :disabled="!selectedFile || uploading" class="btn confirm-upload-btn">
        {{ uploading ? '上传中...' : '确认上传' }}
      </button>
      <p v-if="uploadError" class="error-message">{{ uploadError }}</p>
    </div>

    <div class="background-list">
      <div v-for="(bg, index) in backgrounds" :key="index" class="background-item">
        <img :src="bg" alt="Background Image" class="background-thumbnail" @click="openModal(bg)">
        <div class="background-actions">
          <button @click="handleDelete(bg)" class="btn delete-btn">删除</button>
        </div>
      </div>
    </div>

     <!-- Modal for enlarged image -->
    <div v-if="showModal" class="modal" @click.self="closeModal">
      <span class="close-btn-modal" @click="closeModal">&times;</span>
      <img :src="modalImageUrl" alt="Enlarged Preview" class="modal-content" :style="{ transform: `scale(${zoomLevel})` }" @wheel.prevent="handleWheel">
    </div>  
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getBackgrounds, uploadBackground, deleteBackground } from '../../api';

const backgrounds = ref([]);
const selectedFile = ref(null);
const uploading = ref(false);
const uploadError = ref('');
const fileInput = ref(null);
const previewUrl = ref(null);
const showModal = ref(false);
const modalImageUrl = ref('');
const zoomLevel = ref(1);
zoomLevel.value = 1;

onMounted(() => {
  fetchBackgrounds();
});

async function fetchBackgrounds() {
  try {
    const response = await getBackgrounds();
    backgrounds.value = response.data;
  } catch (error) {
    console.error('Failed to fetch backgrounds:', error);
  }
}


function clearPreview() {
  selectedFile.value = null;
  previewUrl.value = null;
  if (fileInput.value) {
    fileInput.value.value = '';
  }
}

function openModal(imageUrl) {
  modalImageUrl.value = imageUrl;
  showModal.value = true;
}

function closeModal() {
  showModal.value = false;
  modalImageUrl.value = '';
}

function handleWheel(event) {
  const zoomSpeed = 0.1;
  if (event.deltaY < 0) {
    zoomLevel.value += zoomSpeed;
  } else {
    zoomLevel.value = Math.max(0.1, zoomLevel.value - zoomSpeed);
  }
}  

function handleFileChange(event) {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file;
    previewUrl.value = URL.createObjectURL(file);
    uploadError.value = '';
  }
}

function triggerFileInput() {
  fileInput.value.click();
}

async function handleUpload() {
  if (!selectedFile.value) return;

  uploading.value = true;
  uploadError.value = '';

  try {
    await uploadBackground(selectedFile.value);
    selectedFile.value = null;
    previewUrl.value = null; // Clear preview
    fileInput.value.value = ''; // Reset file input
    fetchBackgrounds(); // Refresh the list
  } catch (error) {
    uploadError.value = error.response?.data?.message || 'Upload failed';
    console.error('Upload error:', error);
  } finally {
    uploading.value = false;
  }
}

async function handleDelete(backgroundUrl) {
  const filename = backgroundUrl.split('/').pop();
  if (confirm(`确定要删除背景图片 ${filename} 吗？`)) {
    try {
      await deleteBackground(filename);
      fetchBackgrounds(); // Refresh the list
    } catch (error) {
      console.error('Delete error:', error);
      alert('删除失败');
    }
  }
}
</script>

<style scoped>
.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  max-width: 90vw;
  max-height: 90vh;
  object-fit: contain;
  transition: transform 0.2s ease-out;
}

.close-btn-modal {
  position: absolute;
  top: 20px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
  cursor: pointer;
}

.preview-image,
.background-thumbnail {
  cursor: pointer;
}

.preview-section {
  margin-top: 15px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.preview-header h4 {
  margin: 0;
}

.clear-btn {
  background-color: #f39c12;
  color: white;
  padding: 5px 10px;
}

.clear-btn:hover {
  background-color: #e67e22;
}

.preview-image {
  max-width: 200px;
  max-height: 120px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.background-manage {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.upload-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-input {
  display: none;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-btn {
  background-color: #3498db;
  color: white;
}

.upload-btn:hover {
  background-color: #2980b9;
}

.confirm-upload-btn {
  background-color: #2ecc71;
  color: white;
}

.confirm-upload-btn:hover {
  background-color: #27ae60;
}

.confirm-upload-btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.error-message {
  color: #e74c3c;
  margin: 0;
}

.background-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.background-item {
  width: 200px;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #ddd;
}

.background-thumbnail {
  width: 100%;
  height: 120px;
  object-fit: cover;
  display: block;
}

.background-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px;
  display: flex;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.background-item:hover .background-actions {
  opacity: 1;
}

.delete-btn {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 3px;
  cursor: pointer;
}

.delete-btn:hover {
  background-color: #c0392b;
}
</style>
